package com.zx.platform.controller;

import com.zx.platform.service.MenusService;
import com.zx.platform.service.OperatorInfoService;
import com.zx.platform.service.domain.LoginDomain;
import com.zx.platform.service.domain.ManageSessionDomain;
import com.zx.platform.service.domain.MenusDomain;
import com.zx.platform.service.model.MenusModel;
import com.zx.platform.service.model.OperatorInfoModel;
import com.zx.platform.utils.DesUtil;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.verifycode.VerifyCodeHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller
@RequestMapping("/manage/login")
public class LoginController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(LoginController.class);

	public static List<MenusModel> allMenus = new ArrayList();

	@Autowired
	private OperatorInfoService operatorInfoService;

	@Autowired
	private MenusService menusService;

	/**
	 * EewgJEHgYZY=   -----  2 
	 * @param loginDomain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/toLogin")
	public String login(LoginDomain loginDomain, Model model,
			HttpServletRequest request) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		try {
			// add by wenjw 2014.9.19
			// 登录的时候查出所有菜单，为选择菜单时的样式服务，舍弃cookie.在SecurityManageFilter中用到
			MenusModel menusModel = new MenusModel();
			// 改成每次登录重新设置
			// if (allMenus == null || allMenus.size() <= 0) {
			allMenus = menusService.getAllList();
			// }

			String requestIp = "";
			// 基础验证
			if (StringUtils.isBlank(loginDomain.getUserName())
					|| StringUtils.isBlank(loginDomain.getPassWord())
					|| StringUtils.isBlank(loginDomain.getVerifyCode())) {
				model.addAttribute("errorMsg", "信息输入不完整");
				log.debug("信息输入不完整");
				return "/login";
			}

			// 验证码验证
			if (!VerifyCodeHelper.checkVerifyCode(loginDomain.getVerifyCode(),
					request.getSession())) {
				model.addAttribute("errorMsg", "验证码输入不正确");
				log.debug("验证码输入不正确");
				return "/login";
			}

			requestIp = PmpUtils.getIpAddr(request);

			// 尝试登陆
			OperatorInfoModel operatorInfoModel = getOperatorInfoModel(loginDomain);

			List<OperatorInfoModel> userList = (List<OperatorInfoModel>) operatorInfoService.passOrNotByModel(operatorInfoModel);
			ManageSessionDomain manageSessionDomain = new ManageSessionDomain();
			if (null != userList && userList.size() == 1) {
				operatorInfoModel = userList.get(0);
				if("S".equals(operatorInfoModel.getStatus())){
					model.addAttribute("errorMsg", "当前用户已被关闭，请联系管理员!");
					return "/login";
				}
				manageSessionDomain.setOperatorInfoModel(operatorInfoModel);
				//用户-角色-菜单过滤
				List<MenusModel> menusModelList = operatorInfoService.getMenuListByOperatorId(operatorInfoModel.getOperatorId());

				// 更新上次登录时间
				OperatorInfoModel param = new OperatorInfoModel();
				param.setOperatorId(operatorInfoModel.getOperatorId());
				param.setLastLogintime(new Date());
				operatorInfoService.update(param);

				manageSessionDomain.setMenusDomain(getMenusList(menusModelList));
				request.getSession().setAttribute("_REQIP_", requestIp);
				request.getSession().setAttribute("_LOGONUSER_",
						manageSessionDomain);
				//得到当前登录人拥有权限的第一个菜单并跳转
				List<MenusDomain> menusDomainList = getMenusList(menusModelList);
				if(menusDomainList!=null&&menusDomainList.size()>0){
					MenusDomain firstMenu = menusDomainList.get(0);
					return "redirect:"+firstMenu.getUrl();
				}
				return "redirect:/manage/mainPage/main";
			}else {
				model.addAttribute("errorMsg", "用户名或密码错误");
			}
			return "/login";
		} catch (Exception e) {
			model.addAttribute("errorMsg", "系统内部异常");
			log.info("系统内部异常", e);
			return "/login";
		}
	}

	/**
	 * 获取 OperatorInfoModel
	 * 
	 * @param loginDomain
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	private OperatorInfoModel getOperatorInfoModel(LoginDomain loginDomain)
			throws Exception, UnsupportedEncodingException {
		OperatorInfoModel operatorInfoModel = new OperatorInfoModel();
		operatorInfoModel.setLoginName(loginDomain.getUserName());
		operatorInfoModel.setLoginPassword(DesUtil.encrypt(
				loginDomain.getPassWord(), null));
		return operatorInfoModel;
	}

	@RequestMapping("/verify")
	public String verfiy(HttpServletRequest request) {
		VerifyCodeHelper.createVerifyCode(request.getSession());
		return "jsp/platform/verifycode/showverifycode";
	}

	/**
	 * 菜单列表 去重 排序 分组
	 * 
	 * @param MenuModelList
	 * @return
	 */
	private List<MenusDomain> getMenusList(List<MenusModel> MenusModelList) {

		// list排序
		Collections.sort(MenusModelList, new Comparator() {
			public int compare(Object o1, Object o2) {
				return ((MenusModel) o1).getOrders().compareTo(
						((MenusModel) o2).getOrders());
			}
		});

		Map keyContain = new HashMap();
		List<MenusDomain> menusDomainList = new ArrayList<MenusDomain>();
		Map map = new HashMap();
		for (MenusModel oo : MenusModelList) {
			// 去除重复菜单
			if (null != keyContain.get(oo.getMenuId())) {
				continue;
			} else {
				keyContain.put(oo.getMenuId(), "");
			}
			if (null != map.get(oo.getMenuType())) {
				MenusDomain menusDomain = (MenusDomain) map
						.get(oo.getMenuType());
				menusDomain.getMenus().add(oo);
			} else {
				MenusDomain menusDomain = new MenusDomain();
				menusDomain.setMenuType(oo.getMenuType());
				menusDomain.setUrl(oo.getUrl());
				List<MenusModel> MenuModels = new ArrayList<MenusModel>();
				MenuModels.add(oo);
				menusDomain.setMenus(MenuModels);
				map.put(oo.getMenuType(), menusDomain);
			}
		}

		// 转list
		for (Object key : map.keySet()) {
			menusDomainList.add((MenusDomain) map.get(key));
		}
		// list排序
		Collections.sort(menusDomainList, new Comparator() {
			public int compare(Object o1, Object o2) {
				if (StringUtils.isNotBlank(((MenusDomain) o1).getMenuType())
						&& StringUtils.isNotBlank(((MenusDomain) o2)
								.getMenuType())) {
					Integer type1 = Integer.valueOf(((MenusDomain) o1)
							.getMenuType());
					Integer type2 = Integer.valueOf(((MenusDomain) o2)
							.getMenuType());
					return type1.compareTo(type2);
				} else {
					return ((MenusDomain) o1).getMenuType().compareTo(
							((MenusDomain) o2).getMenuType());
				}

			}
		});
		// 处理二级菜单　add by wenjw 2014.9.16

		for (MenusDomain md : menusDomainList) {
			List subMenuTypes = new ArrayList();
			List<MenusModel> MenuModels = md.getMenus();

			for (MenusModel mm : MenuModels) {
				String subMenuType = mm.getSubMenuType();
				if (!subMenuTypes.contains(subMenuType)) {
					subMenuTypes.add(subMenuType);
				}
			}
			md.setSubMenuTypes(subMenuTypes);
		}
		return menusDomainList;
	}
}
